package com.java2001.controller;


import com.java2001.mapper.UserMapper;
import com.java2001.pojo.User;
import com.java2001.service.UserService;
import com.java2001.utils.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.Account;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.Arrays;


@Controller
public class LoginController {

    @Autowired
    private UserService userServiceImpl;

    /**
     * 跳转到登陆页
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 登陆页 提交表单
     */
    @RequestMapping("/login")
    public String login(String username, String password, Model model) {


        Subject subject = SecurityUtils.getSubject();

        User u = userServiceImpl.queryUserById(username);
        if (u != null) {
            //根据salt值和用户输入的密码计算加密后的密码
            String salt = u.getSalt();
            password = new SimpleHash("md5", password, salt, 2).toString();
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //将用户名和密码通过token传给shiro进行认证
            subject.login(token);
            User user = (User) subject.getPrincipal();
            //往session里传值
            subject.getSession().setAttribute("user", user);
            return "redirect:index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("msg", "密码有误");
            return "login";
        }

    }

    /**
     * 跳转到注册页
     */
    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    /**
     * 登陆页 提交表单
     */
    @RequestMapping({"/register", "/user/addUser"})
    public String register(String username,
                           String password,
                           Integer role,
                           Model model,
                           HttpServletRequest request) throws ParseException {


        String uri = request.getRequestURI();
        System.out.println("uri == " + uri);

        //存在此用户
        if (userServiceImpl.queryUserById(username) != null) {
            model.addAttribute("msg", "已存在此用户");
            return uri.equals("/register") ? "register" : "user/users";
        } else {    //不存在此用户
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRole(role);
            userServiceImpl.insertUser(user);

            if (uri.equals("/register")) {
                model.addAttribute("msg", "注册成功，请登录。");
                return "login";
            } else {
                // attributes.addFlashAttribute("msg", "添加用户成功。");
                // model.addAttribute("msg", "添加用户成功。");
                return "redirect:/user/users";
            }
        }
    }

    /**
     * 注销
     */
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:index";
    }
}
